iT邦幫忙

2023 iThome 鐵人賽

DAY 8
1

目前已經將新增和取得文章的API完成,接著我們要來開發修改和刪除文章的API

大綱

  1. 更新文章API開發
  2. 刪除文章API開發

https://ithelp.ithome.com.tw/upload/images/20230923/20136558RVJiC8QIjt.png

1.更新文章API開發

posts-controller.js下新增updatePost的邏輯

exports.updatePost = async (req, res, next) => {
  try {
    const { postId } = req.params; 

    if (!postId) {
      return next(new HttpError("PostId is required", 400));
    }

    const { title, tags, content, coverImage, authorId } = req.body;

    // 檢查文章是否存在
    const post = await Post.findById(postId);
    if (!post) {
      return next(new HttpError("Post not found", 404));
    }

    // 更新文章資料
    if (title && title.trim() !== "") {
      post.title = title;
    }

    if (tags && Array.isArray(tags) && tags.length !== 0) {
      post.tags = tags;
    }

    if (content && content.trim() !== "") {
      post.content = content;
    }

    if (coverImage) {
      post.coverImage = coverImage;
    }

    await post.save();

    res.status(200).json(post);
  } catch (error) {
    console.log(error);
    next(new HttpError("Server error", 500));
  }
}

exports.getPost = getPost;
exports.createPost = createPost;
exports.updatePost = updatePost;

我們先前已經有在post-routes.js新增更新文章的route,將剛剛建立的controller引入就完成了

//post-routes.js

const express = require('express');
const router = express.Router();
const postController =  require('../controllers/posts-controller');

...(略)

//@router PUT /api/posts/:postId
//@desc 更新文章
//@access Public
router.put("/:postId", postController.updatePost);
module.exports =  router;

在Postman上測試

更新前
https://ithelp.ithome.com.tw/upload/images/20230923/20136558q1dxllDFt0.jpg

更新後
https://ithelp.ithome.com.tw/upload/images/20230923/20136558ZeMdEJ0zDq.jpg

2.刪除文章API開發

一樣在posts-controller.js下新增deletePost的邏輯

//posts-controller.js

//前面都是用const宣告mockpost,因為刪除會改變裡面的內容,所以需要改為let才能正常執行刪除。
let MOCK_POSTS = [
    {
        id: 'p1',
        title: '文章1',
        tags: ['frontend'],
        content:'ChatGPT'
    },
    {
        id: 'p2',
        title: '文章2',
        tags: ['lifeStyle'],
        content:'Micro frontend'
    }
]

...(略)

const deletePost =  (req,res,next)=>{
    const postId = req.params.postId;
    const postIndex = MOCK_POSTS.findIndex(post => post.id === postId);

    if(postIndex < 0){
        return next(new HttpError('刪除失敗:此id的文章不存在', 404));
    }

    MOCK_POSTS.filter(post => post.id !== postId);
    res.status(201).json({message: '刪除成功'});
}


exports.getPost = getPost;
exports.createPost = createPost;
exports.updatePost = updatePost;
exports.deletePost = deletePost;

接著在post-routes.js引入剛剛建立的controller

//post-routes.js

const express = require('express');
const router = express.Router();
const postController =  require('../controllers/posts-controller');

...(略)

//@router DELETE api/posts
//@desc 刪除文章
//@access Public*/
router.delete("/:postId", postController.deletePost);

module.exports =  router;

在Postman上測試

https://ithelp.ithome.com.tw/upload/images/20230923/20136558MQcO8CcfxW.jpg


上一篇
[Day7] 文章新增API開發並使用Postman測試
下一篇
[Day9]連接資料庫(使用MongoDB和Mongoose)
系列文
初探全端之旅: 以MERN技術建立個人部落格31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言